<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <p>封装cookie</p>
    <script>
        // 设置cookie--如果key相同，会用新的值覆盖老的值；如果key不同，就新增
        function setCookie(key, val, time) {
            var date = new Date(time);
            document.cookie = key + '=' + val;
        }

        // 获取cookie
        function getCookie(key) {
            var cookieStr = document.cookie;
            var cookieArr = cookieStr.split(';');
            var obj = {};
            // 遍历数组，将数组中的每一项分割成两小项，第一个是对象的key，第二个是对象的value
            for (var i = 0; i < cookieArr.length; i++) {
                var arr2 = cookieArr[i].split('=');
                // 方括号表示对象的key是变量
                obj[arr2[0].trim()] = arr2[1]
            }
            return obj[key]
        }
    </script>
</body>

</html>